<script setup lang="ts">
import { ref, defineEmits, reactive, nextTick, watch } from "vue"
import { $t } from '@vben/locales';
import { getExamListApi } from "#/api/manage/paper"
import CustomPopover from '#/components/custom-popover.vue';
import { trimStringParams } from '#/utils/trimStringParams'

defineOptions({ name: 'Dialog' })
const props = defineProps({
  paperIdList: {
    type: Array,
    default: ()=> []
  },
  certificationId:{
    type: String,
    default: ()=> ''
  }
});

const dialogVisible = ref(false)
const paperTableRef = ref()
const loading = ref(false)
const tableData = ref<any>([])
const defaultSelectionList = ref<any>([])
const selectionList = ref<any>([])

const queryData = reactive({
  name: ''
})
const pageData = reactive({
  total: 0,
  curPage: 1,
  pageSize: 10
})

const inint = (list: any) => {
  defaultSelectionList.value = list ?? []
  onQuery()
  dialogVisible.value = true
}

const setDefaultSelections = () => {
  tableData.value.forEach((row: { papersId: any }) => {
    if (defaultSelectionList.value.find(((item: { papersId: any }) => item == row.papersId))) {
      paperTableRef.value.toggleRowSelection(row, true);
    }
  });
}

const onQuery = () => {
  loading.value = true
  const trinsParamsData = trimStringParams(queryData)
  const params = {
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  } as any
  if (props.certificationId) {
    params.certificationIdList = props.certificationId
  }
  Object.keys(trinsParamsData).forEach(key => {
    const kVal = trinsParamsData[key as keyof typeof trinsParamsData]
    if (kVal) {
      params[key] = kVal
    }
  })
  getExamListApi(params).then((res) => {
    const { data, pageInfo } = res
    tableData.value = data
    pageData.total = pageInfo.totalRows
    if (defaultSelectionList.value.length > 0) {
      nextTick(() => {
        setDefaultSelections();
      })
    }
  }).finally(() => {
    loading.value = false
  })
}

watch(tableData, async (newVal:any) => {
  await nextTick(); // 等待表格渲染
  if (paperTableRef.value) {
    paperTableRef.value.clearSelection(); // 先清空
    newVal.forEach((row:any) => {
      if (props.paperIdList.includes(row.id)) {
        paperTableRef.value.toggleRowSelection(row, true);
      }
    });
  }
}, { immediate: true });

const handleClose = () => {
  pageData.pageSize = 10
  pageData.curPage = 1
  tableData.value = []
  selectionList.value = []
  defaultSelectionList.value = []
  paperTableRef.value!.clearSelection()
  dialogVisible.value = false
}

const submit = () => {
  emit('choseExamType', selectionList.value)
  handleClose()
}

const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  onQuery()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  onQuery()
}

const handleSelectionChange = (data: any) => {
  selectionList.value = data
}
defineExpose({ inint })

const emit = defineEmits(['choseExamType']);

</script>
<template>
  <el-dialog v-model="dialogVisible" align-center :title="$t('exam.selectPaper')" width="800"
    :close-on-click-modal="false" :before-close="handleClose">
    <div class="w-full h-auto flex flex-col pb-[24px]">
      <div class="flex mb-[16px]">
        <el-input type="text" :maxlength="50" clearable v-model="queryData.name"
          :placeholder="`${$t('common.inputPhTxt', [$t('paper.paperNameTxt')])}/${$t('exam.linkCert')}`"
          class="mr-[20px]"></el-input>
        <el-button type="primary" @click="onQuery">{{ $t('common.searchTxt') }}</el-button>
      </div>
        <el-table class="flex-1" ref="paperTableRef" row-key="id" v-loading="loading" :data="tableData" max-height="450px"
          @selection-change="handleSelectionChange">
          <el-table-column header-align="center" align="center" width="60" type="selection"></el-table-column>
          <el-table-column prop="papersName" :label="$t('paper.paperNameTxt')" min-width="150">
            <template #default="{ row }">
              <CustomPopover :strTxt="row.papersName ?? '--'"></CustomPopover>
            </template>
          </el-table-column>
          <el-table-column prop="certificationName" :label="$t('exam.linkCert')" min-width="104">
            <template #default="{ row }">
              <CustomPopover :strTxt="row.certificationName ?? '--'"></CustomPopover>
            </template>
          </el-table-column>
        </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :current-page="pageData.curPage" :total="pageData.total"></el-pagination>
    </div>
    <template #footer>
      <div>
        <el-button @click="handleClose">
          {{ $t('common.cancelTxt') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
</style>
